package com.smart.tool.excel;


import cn.idev.excel.EasyExcel;
import cn.idev.excel.write.metadata.WriteSheet;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;

/**
 * @Author xiaoqiang
 * @Version ExcelGenerateUtils.java, v 0.1 2024年11月11日 下午12:19 xiaoqiang
 * @Description: TODO excel文件生成
 */
public class ExcelGenerateUtils {

    public static <T> File generateFile(File file, List<T> dataList, Class<T> clazz) {
        if (CollectionUtils.isEmpty(dataList)) {
            throw new IllegalArgumentException("dataList is null or empty");
        }
        if (file == null) {
            throw new IllegalArgumentException("file is null");
        }
        if (clazz == null) {
            throw new IllegalArgumentException("clazz is null");
        }
        EasyExcel.write(file,clazz)
                .sheet("sheet1")
                .doWrite(dataList);
        return file;

    }

    public static <T> File generateFile(Collection<T> dataList, Class<T> clazz) {

        try {
            File file = File.createTempFile("excel", ".xlsx");
            WriteSheet writeSheet = new WriteSheet();
            EasyExcel.write(file, clazz).build().write(dataList, writeSheet);
            return file;
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }


    public static <T> File generateFile(Collection<T> dataList, List<List<String>> heads) {

        try {
            File file = File.createTempFile("excel", ".xlsx");
            EasyExcel.writerSheet().head(heads).doWrite(dataList);
            return file;

        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }


    /**
     * 读取excel文件
     *
     * @param fileName 文件路径
     * @param clazz    对象名称
     * @param <T>
     * @return
     */
    public static <T> List<T> readExcel(String fileName, Class<T> clazz) {
        final List<T> allDataSources = Lists.newArrayList();
        EasyExcel.read(fileName, clazz, ExcelEventListenerUtils.getListener(
                new Consumer<List<T>>() {
                    @Override
                    public void accept(List<T> objects) {
                        allDataSources.addAll(objects);
                    }
                }, false, 300000
        )).sheet().doRead();
        return allDataSources;
    }
}
